<?php
namespace app\modules\company\models;
use app\models\Basic;

use Yii;
use yii\base\Model;

class CompanySearch extends Company
{
    public $begin_time;
    public $end_time;

    public function rules()
    {
        return [
            ['company_name', 'default', 'value' => ''],
            ['company_name', 'string', 'message' => 'company_name必须是字符串',
                             'max' => 64, 'tooLong' => 'company_name最长64位'],
            ['province', 'default', 'value' => ''],
            ['province', 'string', 'message' => 'province必须是字符串', 
                         'max' => 16, 'tooLong' => 'province最长16位'],
            ['city', 'default', 'value' => ''],
            ['city', 'string', 'message' => 'city必须是字符串', 
                     'max' => 16, 'tooLong' => 'city最长16位'],
            ['state', 'default', 'value' => ''],
            ['state', 'integer', 'message' => 'state必须为数字，或数字字符串'],
            ['state', 'in', 'range' => array(1, 2, 3, 4), 'message' => 'state值必须在1,2,3,4中才选择'],
            ['begin_time', 'date', 'format'=>'yyyy-MM-dd', 'message' => 'begin_time非yyyy-MM-dd格式'],
            ['end_time', 'date', 'format'=>'yyyy-MM-dd', 'message' => 'end_time非yyyy-MM-dd格式'],
        ];
    }

    public function scenarios()
    {
        return Model::scenarios();
    }

    public function search($params)
    {
        $data['CompanySearch'] = $params;
        // P($data);

        $query = Company::find();

        if (!($this->load($data) && $this->validate())) {
            return false;
        }
        // P($this);

        if( ($this->userInfo['comid'] != '00000000') or !isset($this->flag) ){
            // P($this->userInfo['com_id']);
            /*注释原因： 改成下面的写法，不需要到数据取com_id,直接在session里取*/
            // $company = Company::find()->select('com_id')
            //                           ->where('comid = :id', [':id' => $this->userInfo['comid']])->one();
            // if(!is_null($company)){
            //     $query -> andFilterWhere([
            //         '{{%company}}.recommend' => $company->com_id,
            //     ]);
            // }
            $query -> andFilterWhere([
                '{{%company}}.recommend' => $this->userInfo['com_id'],
            ]);
        }

        if(!empty($this->end_time)){
            $this->end_time .= ' 23:59:59';
        }

        $query -> andFilterWhere(['like', '{{%company}}.company_name', $this->company_name]);
        $query -> andFilterWhere([
            '{{%company}}.province' => $this->province,
            '{{%company}}.city' => $this->city,
            '{{%company}}.state' => $this->state,
        ]);
        $query -> andFilterWhere(['>=', '{{%company}}.add_time', $this->begin_time])
               -> andFilterWhere(['<=', '{{%company}}.add_time', $this->end_time]);

        return $query;
    }

    
}